<?php

$username = Path::get('//user/user_name', 'flow');
$user_password = Path::get('//user/user_password', 'flow');
$user_id = Path::get('//user/user_id', 'flow');
$roles = Path::get('//role/name', 'flow');

//$roles = Array('user','root','admin');
$account_id = Path::get('//account/account_id','flow');
$account_domain_name = Path::get('//account/domain_name','flow');
$logo = Path::get('//account/logo','flow');
$employer_id = Path::get('//account/employer_id','flow');
$mime_type = Path::get('//account/mime_type','flow');
$key = Path::get('//key','flow');
$last_database_update = Path::get('//account/database_datetime','flow');

// set IV
if(function_exists('mcrypt_get_iv_size')) { 
	$iv_size = mcrypt_get_iv_size(MCRYPT_XTEA, MCRYPT_MODE_ECB);
	$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
} else { 
	$iv="";
}

//echo "roles:";
//print_r($roles);

// Remove duplicate roles
if(is_array($roles)) { 
	$tmparr = array_unique($roles);
	
	$i=0;
	
	foreach ($tmparr as $v) {
		$newarr[$i] = $v;
		$i++;
	}  

} else { 
	$newarr=$roles;
}


$auth = &new Auth();
        
if(!$auth->registerUser($newarr))
{
    trigger_error(Error::getError(). ' in login.php', WARNING);         
}

$auth->setSessionData("account_id", $account_id);
$auth->setSessionData("account_domain_name", $account_domain_name);

$auth->setSessionData("key", $key);
$auth->setSessionData("iv", $iv);
$auth->setSessionData("logo", $logo);
$auth->setSessionData("mime_type", $mime_type);
$auth->setSessionData("user_id", $user_id);
$auth->setSessionData("employer_id", $employer_id);
$auth->setSessionData("user_name", $username);
$auth->setSessionData("last_database_update", $last_database_update);

Flow::add("account_id",$account_id);

//go back where we were called from
$redirect = Path::get('//_post/redirect', 'flow');
$redirect = urldecode($redirect);
$redirect = str_replace("{}","/",$redirect);
$redirect = str_replace("}{","&",$redirect);
$redirect = preg_replace('/^\//','',$redirect);
	
	

if(isset($_SESSION['NX_AUTH']['requestedUrl'])) { 
    $redirect = $_SESSION['NX_AUTH']['requestedUrl'];	
} else { 
    $redirect = Config::get("//default");
}



header("Location: $redirect");


   echo '<pre>';
   print_r($auth->sessionData);
	print_r($_SESSION);
	echo " <br/> redirect: $redirect";
	//print_r($GLOBALS);
   echo '</pre>';





?>
